import { Vector3 } from "../math/Vector3";
import { handleUeMsgError, isClientApp, post, registerMessageHandle, registerReady } from "../utils/Client";
import { Weather } from "../weather/Weather";
import { Light } from "../lights/Light";
import { Camera } from "../cameras/Camera";
import { OrbitControls } from "../cameras/OrbitControls";
import { ClientMsgHandel, ClientMsgOff, ClientMsgOn } from "../events/ClientMsgHandle";

/**DTJsBridgeContext */
class DTJsBridgeContext {
  isReady = false;

  /**天气 */
  weather: Weather;

  /**控制器 */
  controls: OrbitControls;

  /**摄像机 */
  camera: Camera;

  /**灯光 */
  lights: Array<Light>;

  constructor(options?) {
    if (isClientApp()) {
      this.postReady();
      registerMessageHandle((result) => {
        if (typeof result == "string") {
          result = JSON.parse(result);
        }
        console.log("ueToWeb", result);
        ClientMsgHandel(result);
      });
    } else {
      console.warn("未检测到客户端");
      this.isReady = false;
    }
  }
  /**初始化相机 */
  initCamera() {
    return post("preview_player", { key: "get" }).then((result) => {
      this.camera = new Camera(result);
      return this.camera;
    });
  }
  /**初始化控制 */
  initControls() {
    return post("preview_controller", { key: "get" }).then((result) => {
      this.controls = new OrbitControls(Object.assign(result, { camera: this.camera }));
      return this.controls;
    });
  }
  /**初始灯光信息 */
  initLight() {
    return post("preview_light", { key: "get" }).then((result) => {
      console.log("lights", result);
      this.lights = result.lights.map((item) => {
        return new Light(item);
      });
      console.log("lights", this.lights);
      return this.lights;
    });
  }
  async init() {
    //天气
    this.weather = new Weather();
    try {
      //初始化控制器
      await this.initControls();

      //初始化摄像机
      await this.initCamera();

      //初始灯光  //灯光返回值错误，应列表
      await this.initLight();
    } catch (error) {
      console.error(error);
    }
    return this;
  }
  private postReady() {
    return post("completed");
  }
  /**
   * 取消事件
   * @param eventKey 事件key
   */
  off(eventKey) {
    ClientMsgOff(eventKey);
  }

  /**
   * 注册事件处理
   * @param {*} eventKey 事件key
   * @param {*} action 事件处理函数
   */
  on(eventKey, call) {
    ClientMsgOn(eventKey, call);
  }
}

/**会话上下文 */
const DTJsBridge = new DTJsBridgeContext();

export { DTJsBridge, DTJsBridgeContext };
